<template>
	<!-- 需要展示的列数据分为三部，第一个是标题、副标题；第二部分是需要合并的列数据；第三部分是无需合并的列数据 -->
	<view class="dilCard">
		<view class="card" v-for="(cardItem, index) in dataListDisposed" :key="index">
			<uni-card :title="cardItem[columnDataMap.cardTitle] || ''" :extra="cardItem[columnDataMap.cardTipTitle] || ''" margin="10rpx" padding="4rpx">
				<view class="topRow">
					<!-- 需要合并的列数据，展示上的合并，数据上的合并 -->
					<view v-for="(item, index) in disposeRowData(columnDataMap.topData, cardItem)" :key="item.data_id" @click="onclick(item, cardItem)" class="rowItemWhole">
						<text class="label">{{ item.label }}</text>
						<text class="tag">|</text>
						<text class="value" :class="{ importantClass: item.isImportant == 1, imageClass: item.label.includes('图片') }" @click.stop="previewImage(item, cardItem)">
							{{ item.label.includes('图片') ? '点击查看' : cardItem[item.prop] }}
						</text>
					</view>
				</view>
				<view slot="actions" class="card-actions" v-if="cardSlotListEnd(cardItem).length > 0">
					<view class="card-actions-item" v-for="(sitem, sindex) in cardSlotListEnd(cardItem)" @click="actionsClckDebounce(sitem, cardItem)" :key="sindex">
						<uni-icons custom-prefix="iconfont" :type="sitem.icon" size="18" color="#00aded" v-if="sitem.icon != null && sitem.icon.includes('wl')"></uni-icons>
						<uni-icons :type="sitem.icon" size="18" color="#00aded" v-else-if="sitem.icon != null"></uni-icons>
						<text class="card-actions-item-text">{{ sitem.label }}</text>
					</view>
				</view>
			</uni-card>
			<!-- <view class="watermark-canvas">
				<canvas id="qwer" canvas-id="watermark-canvas" style="width:10px,height:10px;position: fixed !important; left: 100%" />
			</view> -->
		</view>
		<view class="pageClass">
			<uni-pagination v-bind="pageProp" v-if="dataListDisposed.length > 0 && pageProp.total > 20" @change="changePage" />
		</view>
	</view>
</template>

<script>
import { formatDate } from '@/utils/utils.js';
import { debounce, previewImage, dataURLtoTempPath, base64ToPath } from '@/utils/utils.js';
import { myRequest } from '@/utils//api.js';
export default {
	name: 'dil-card',
	data() {
		return {
			preHiddenData: [],
			pageProp: {
				total: 50,
				pageSize: 50,
				current: 1,
				showIcon: true
			},
			columnData: [],
			dataList: []
		};
	},
	props: {
		cardItem: {
			default() {
				return {};
			},
			require: true
		},
		cardSlotList: {
			default() {
				return [];
			},
			require: false
		},
		requestUrl: {
			default: ''
		},
		requestQuery: {
			default() {
				return {};
			}
		},
		columnDataList: {
			default() {
				return [];
			},
			require: false
		},
		rowDataList: {
			default() {
				return [];
			},
			require: false
		},
		totalNum: 0,
		keys: {
			default: 'new',
			require: false
		}
	},
	created() {
		this.preHiddenData = JSON.parse(uni.getStorageSync('preHiddenData'));
	},
	mounted() {
		//挂载防抖
		this.getRequestDataDebounce = debounce(() => {
			this.getRequestData();
		}, 1500);
		this.actionsClckDebounce = debounce((value, value2) => {
			this.actionsClck(value, value2);
		}, 200);
		uni.$on('onShow', (data) => {
			this.getRequestDataDebounce();
		});
		this.getRequestDataDebounce();
	},
	beforeDestroy() {
		uni.$off('onShow');
	},
	watch: {
		requestUrl() {
			this.getRequestDataDebounce();
		},
		requestQuery: {
			deep: true,
			handler(newValue, oldValue) {
				this.pageProp.current = 1;
				this.getRequestDataDebounce();
			},
			immediate: false
		},
		columnDataMap: {
			handler(newValue) {
				this.$emit('update:importData', newValue.importData);
			}
		}
	},
	computed: {
		//首先判断是否启用合并,如果有一个为1，则说明启用合并
		cardSlotListEnd(item) {
			return function (item) {
				return this.cardSlotList
					.filter((e) => {
						return !e.showCondition || eval(e.showCondition);
					})
					.filter((e) => {
						return e.noPre || this.preHiddenData.includes(e.emitEvent);
					});
			};
		},
		columnDataMap() {
			return this.columnData.reduce(
				(prev, item) => {
					if (item.titleType == 'title') {
						prev.cardTitle = item.prop;
					} else if (item.titleType == 'extraTitle') {
						prev.cardTipTitle = item.prop;
					} else {
						prev.topData.push(item);
					}
					if (item.isImportant == 1) {
						prev.importData.push(item);
					}
					return prev;
				},
				{
					cardTitle: '标题',
					cardTipTitle: '副标题',
					topData: [],
					buttomData: [],
					importData: []
				}
			);
		},
		// 处理数据，做数据上的合并，即根据列的isMergeCol属性，来判断以哪些数据为基础，来进行数据合并，处理后的数组里面的对象为{...item,childeren:[]}的格式
		dataListDisposed() {
			return this.dataList.reduce((prev, item) => {
				//遍历item的key
				item.children = [];
				let map = {};
				//遍历需要合并的数组元素
				if (prev.length == 0) {
					item.children.push(map);
					prev.push(item);
					return prev;
				}
				item.children.push(map);
				prev.push(item);
				return prev;
			}, []);
		},
		disposeRowData(data, item) {
			return function (data, item) {
				return data.filter((e) => {
					return item[e.prop] != null && item[e.prop] != undefined && item[e.prop] != '';
				});
			};
		}
	},
	methods: {
		//过滤数据
		filterDataList(data) {
			let responseData = [];
			//获取权限数据及公司数据
			let roleCodes = JSON.parse(uni.getStorageSync('roleCodes'));
			//获取公司数据
			let dilCompanyList = JSON.parse(uni.getStorageSync('dilCompanyList'));
			//获取公司数组
			let companyList = dilCompanyList.map((e) => {
				return e.companyId;
			});
			if (dilCompanyList.length == 0) {
				return data;
			}
			if (roleCodes.length == 0) {
				return data;
			}
			if (roleCodes.includes('businessCompany')) {
				//遍历数组
				responseData = data.filter((e) => {
					return e && e.businessCompanyId && companyList.includes(e.businessCompanyId);
				});
				return responseData;
			}
			return data;
		},
		changePage(item) {
			this.pageProp.current = item.current;
			this.getRequestDataDebounce();
		},
		async getRequestData(options) {
			if (!this.requestUrl) {
				console.error('未传入requestUrl');
				return;
			}
			let pageSize = this.pageSize || 20;
			let pageNum = this.pageProp.current || 1;
			let requestUrl = this.requestUrl;
			let apiId = requestUrl.split('apiId=')[1].split('&')[0];
			// 重写requestUrl
			if (!requestUrl.includes('apiId')) {
				console.error('未设置apiId');
			} else {
				requestUrl = requestUrl.split('?')[0] + '?apiId=' + apiId;
			}
			requestUrl = requestUrl + '&pageNum=' + pageNum + '&pageSize=' + pageSize;
			const res = await myRequest({
				url: requestUrl,
				data: this.requestQuery
			}).catch((e) => {
				console.log(e, 'e');
				this.dataList = [];
				this.columnData = [];
			});
			console.log(res, 'res');
			if (res.data.status == 'succeed') {
				uni.pageScrollTo({
					scrollTop: 0, // 滚动到页面的目标位置  这个是滚动到顶部, 0
					duration: 500 // 滚动动画的时长
				});
				this.dataList = res.data.data.list;
				this.columnData = res.data.data.columnData;
				this.$emit('update:columnDataList', this.columnData);
				this.$emit('update:rowDataList', this.dataList);
				this.pageProp.total = res.data.data.total;
				this.$emit('update:totalNum', res.data.data.total);
			} else {
				this.dataList = [];
				this.columnData = [];
				this.$emit('update:totalNum', 0);
				this.$emit('update:columnDataList', this.columnData);
				this.$emit('update:rowDataList', this.dataList);
			}
		},
		onclick(item, cardItem) {
			if (item.label.includes('图片')) {
				this.$emit('imagePreview', cardItem);
			}
		},
		actionsClck(sitem, cardItem) {
			this.$emit(sitem.emitEvent, cardItem);
			let map = {
				...cardItem,
				...sitem.arguments,
				...{
					importData: this.columnDataMap.importData
				}
			};
			this.$emit('emitEvent', sitem.emitEvent, map);
		},
		previewImage(item, cardItem) {
			if (item.label.includes('图片') && cardItem[item.prop]) {
				previewImage(cardItem[item.prop], (data) => {
					if (data.previewList.length > 0) {
						let list = [];
						uni.previewImage({
							urls: data.previewList,
							longPressActions: {
								itemList: ['保存图片'],
								success: function (previewData) {
									if (previewData.tapIndex == 0) {
										uni.saveImageToPhotosAlbum({
											filePath: data.downloadList[previewData.index],
											success: (saveRes) => {
												uni.showToast({
													title: '保存成功',
													icon: 'success',
													duration: 2000
												});
											},
											fail: (saveErr) => {
												uni.showToast({
													title: '保存失败',
													icon: 'error',
													duration: 2000
												});
											}
										});
									}
								}
							}
						});
					} else {
						uni.showToast({
							duration: 2000,
							title: '无图片信息',
							icon: 'error'
						});
					}
				});
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.dilCard {
	/deep/.uni-card {
		border-radius: 40rpx;
	}
	/deep/.uni-card .uni-card__header .uni-card__header-content .uni-card__header-content-title {
		color: #00aded;
		font-weight: 700;
		font-style: 40rpx;
	}
	/deep/.uni-card .uni-card__header .uni-card__header-extra .uni-card__header-extra-text {
		color: #00aded;
		font-weight: 450;
		font-size: 32rpx;
	}
	/deep/.uni-card .uni-card__header {
		border-bottom: 1px #00aded solid;
	}
	padding-bottom: 20rpx;

	.card {
		.topRow,
		.buttomRow {
			display: flex;
			flex-direction: row;
			flex-wrap: wrap;
			width: 100%;
			.rowItemWhole {
				margin-top: 8rpx;
				flex-basis: 100%;
				border-bottom: 1px #b3b3b3 solid;
				.label {
					font-weight: 500;
					color: #000;
					font-size: 36rpx;
				}
				.tag {
					font-weight: 500;
					color: #000;
					font-size: 36rpx;
					margin-left: 10rpx;
				}
				.value {
					font-weight: 500;
					color: #000;
					font-size: 36rpx;
					margin-left: 10rpx;
				}
				.importantClass {
					color: #ff0000;
				}
				.imageClass {
					color: #00aded;
				}
			}
			.rowItemWhole:last-child {
				color: #00aded;
				border-bottom: 0px;
			}
			.rowItemHalf {
				margin-top: 8rpx;
				flex-basis: 50%;
				.label {
					font-weight: 500;
					color: #000;
					font-size: 36rpx;
				}
				.tag {
					font-weight: 500;
					color: #000;
					font-size: 36rpx;
					margin-left: 10rpx;
				}
				.value {
					font-weight: 500;
					color: #000;
					font-size: 36rpx;
					margin-left: 10rpx;
				}
				.importantClass {
					color: #ff0000;
				}
				.imageClass {
					color: #00aded;
				}
			}
		}
		.card-actions {
			display: flex;
			flex-direction: row;
			justify-content: space-around;
			align-items: center;
			height: 45px;
			border-top: 1px #00aded solid;
			.card-actions-item {
				display: flex;
				flex-direction: row;
				align-items: center;
				.card-actions-item-text {
					font-size: 12px;
					color: #666;
					margin-left: 5px;
				}
			}
		}
	}

	.rowItemWhole:last-child {
		color: #00aded;
		border-bottom: 0 !important;
	}
	.pageClass {
		margin-top: 20rpx;
		margin-bottom: 20rpx;
	}
	/deep/ .pageClass .uni-pagination__btn {
		font-weight: 700;
		color: #000;
	}
}
</style>
